<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use fast\Tree;

class Column extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'column';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];
    

    /**
     * @栏目目录树
     */
    public static function getTreeList($selected = [], $map=null, $myid=0, $isShowEdit=0)
    {
        $dpList = collection(self::where($map)->order('weight asc')->select())->toArray();
        $nodeList = [];
        Tree::instance()->init($dpList);
        $dpList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($myid), 'name');
        
        $hasChildrens = [];
        foreach ($dpList as $k => $v)
        {
            if ($v['haschild'])
                $hasChildrens[] = $v['id'];
        }
        $isShowEdit = $isShowEdit==1 ? null : 'style="display: none;"';
        foreach ($dpList as $k => $v) {
            $state = array('selected' => in_array($v['id'], $selected) && !in_array($v['id'], $hasChildrens));
            if (isset($v['id'])){
                $text = '<edit ' . $isShowEdit . '>
                            <a href="column/edit?ids='. $v['id'] .'" class="btn btn-xs btn-success btn-dialog" title="编辑栏目"><i class="fa fa-pencil"></i></a>
                            <a href="column/add?pid='. $v['id'] .'" class="btn btn-xs btn-success btn-dialog" title="添加栏目"><i class="fa fa-plus"></i></a>
                            <a href="javascript:;" data-name="'. $v['name'] .'" class="btn btn-xs btn-danger del" title="删除栏目"><i class="fa fa-trash" id="'. $v['id'] .'" data-name="'. $v['name'] .'"></i></a>
                         </edit>';
                
                $nodeList[] = [
                    'id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#',
                    'text' => "<img src='{$v['image']}' style='width:23px; height:23px;'> " . $text . $v['name'],
                    'type' => 'menu',
                    'state' => $state
                ];
            }
        }
        
        return $nodeList;
    }

    public function getFlagList()
    {
        return ['hot' => __('Hot'), 'top' => __('Top'), 'recommend' => __('Recommend')];
    }    
    
    public function getFlagTextAttr($value, $data)
    {
        $value = $value ?: ($data['flag'] ?? '');
        $valueArr = explode(',', $value);
        $list = $this->getFlagList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }
    
    protected function setFlagAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }
    
}
